//
//  NetworkManager.m
//  QLadder
//
//  Created by xiongguobing on 2019/8/23.
//  Copyright © 2019 qding. All rights reserved.
//

#import "NetworkManager.h"
#import "AFNetworkReachabilityManager.h"

static NetworkManager * manager = nil;

@implementation NetworkManager

+ (id)sharedManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[NetworkManager alloc] init];
        [manager monitorReachabilityStatus];
    });
    return manager;
}

//监测网络状态的方法
- (void)monitorReachabilityStatus
{
    // 开始监测
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 网络状态改变的回调
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"蜂窝网络");
                self.ip = self.currentCity = @"";
                [self getIPAndCity:nil];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI");
                self.ip = self.currentCity = @"";
                [self getIPAndCity:nil];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                break;
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知");
                break;
            default:
                break;
        }
    }];
}

- (void)getIPAndCity:(getIPAndCitySuccess _Nullable)successBlock
{
    if (self.ip.length && self.currentCity.length) {
        if (self.successBlock) {
            self.successBlock(self.ip, self.currentCity);
            return;
        }
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //通过淘宝提供的服务，定位WAN的IP
        NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
        NSData *data = [NSData dataWithContentsOfURL:ipURL];
        if (data) {
            NSDictionary *ipDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSString *ipStr = nil;
            NSLog(@"IPDict:%@",ipDict);
            //获取成功
            if (ipDict && [ipDict[@"code"] integerValue] == 0) {
                ipStr = ipDict[@"data"][@"ip"];
                self.currentCity = ipDict[@"data"][@"city"];
                self.ip = (ipStr ? ipStr : @"");
                if (successBlock) {
                    successBlock(self.ip, self.currentCity);
                }
            }            
        }
    });
}

- (NSString *)port
{
    if (!_port) {
        _port = [NSString stringWithFormat:@"%ld", (long)[kUserDefaults integerForKey:@"randomPort"]];
    }
    return self.port;
}

@end
